package com.stars.easyms.logger.support.logback.util;

import ch.qos.logback.core.encoder.Encoder;
import com.stars.easyms.logger.support.logback.handler.EasyMsLoggingEvent;
import lombok.extern.slf4j.Slf4j;
import net.logstash.logback.Logback11Support;
import net.logstash.logback.encoder.CompositeJsonEncoder;

import java.io.IOException;

/**
 * <p>className: LogStashLogbackUtil</p>
 * <p>description: logstash工具类</p>
 *
 * @author guoguifang
 * @date 2019-11-14 15:38
 * @since 1.4.0
 */
@Slf4j
final class LogStashLogbackUtil {

    static boolean isLogstashEncoder(Encoder encoder) {
        return encoder instanceof CompositeJsonEncoder;
    }

    @SuppressWarnings("unchecked")
    static byte[] encode(EasyMsLoggingEvent event, Encoder encoder) {
        CompositeJsonEncoder compositeJsonEncoder = (CompositeJsonEncoder) encoder;
        if (Logback11Support.isLogback11OrBefore()) {
            try {
                compositeJsonEncoder.doEncode(event);
            } catch (IOException e) {
                log.error("Log stash encode event fail!", e);
            }
        } else {
            return compositeJsonEncoder.encode(event);
        }
        return new byte[0];
    }

    private LogStashLogbackUtil() {
    }
}